var dates;
var data="";
var accord;
var datePicker;
var weeks=new Array('First','Second','Third','Fourth');

function datefunction(d){    
	d = d.split("@#@");
	var obj = $.parseJSON(d[0]);
	var id = d[1];
	dates = obj[id];	
	
/*	var assignmentsobj = dateobj.assignments;
	var courseobj = dateobj.course;
	var testobj = dateobj.test; */
	return true;
}
function appendContent(d,uuid,content){
	d = d.replace(/ /g,'');							
	if($("#"+d).html()==null){
		var contentdiv="<div id='"+d+"'>\
		<div class='"+uuid+"'>\
		"+content+"\
		</div>\
		</div>";
		$("#datecontent").append(contentdiv);
	}
	else{
	if($("."+uuid).html()==null){
							var contentdiv="<div class='"+uuid+"'>\
												  "+content+"\
												 </div>";
								$("#"+d).append(contentdiv);
								
	}
	}
}

function dayView(date){

    var d = date.toDateString();
	d = d.replace(/ /g,'');
	var content = $("#"+d).html();
	var dayli = "<li>"+content+"</li>";
	$("#dayul").html(dayli);
	$(accord).accordion("activate",2);
	$(accord).accordion("resize");
}
function monthView(dat){
  $("#monthul").html('');
//TODO : make the call to this function more dynamic
  var muts = Math.round(dat.getTime() / 1000);
  muts = muts+'';
  var month1 = parseInt(date("m",muts));
  var d = dat.toDateString();
  d = d.replace(/ /g,'');
  var otherdates = $("#datecontent div").not("#"+d);
  var montharray = new Array();

  $(otherdates).each(function(){
	  if($(this).attr('id')!=''){
		  var d2 = $(this).attr('id');
		  var i = 0;
		  d2 = d2.substr(0,3)+' '+d2.substr(3,3)+' '+d2.substr(6,2)+' '+d2.substr(9,4);
		  var uts2 = Math.round((new Date(d2)).getTime() / 1000);
		  uts2=uts2+'';
		  var month2 = parseInt(date("m",uts2));
		  if(month1==month2){
			  //check if it is in the same week
			  
			  var week1 = parseInt(date("W",muts));
			  var week2 = parseInt(date("W",uts2));
			  
			  if(week1 == week2){
				montharray[i] = new Array();
				montharray[i].push(muts);
				montharray[i].push(uts2);
			  }
		  }
	  }	 
  });
 if(montharray.length < 1){
	 montharray[0] = new Array();
	 montharray[0].push(muts);
 }
 for ( i in montharray ){
	 var weekul="";	 
	 for( j in montharray[i]){	
	     var uts = date("D M j Y",montharray[i][j]);	 
	     var dayli = "<li>"+uts+"</li>";
	     weekul+=dayli;			
	 }
	 	 
	 weekul = "<h5>"+weeks[i]+" Week</h5><ul class='week' id='week"+i+"'>"+weekul+"</ul>";	 
	 var monthli="<li>"+weekul+"</li>";	 
	 $("#monthul").append(monthli);
 }    
}
function weekView(dat){	
//TODO : make the call to this function more dynamic
	$("#weekul").html('');
	var uts = Math.round(dat.getTime() / 1000);
	uts = uts+'';
	var week1 = parseInt(date("W",uts));	
	var d = dat.toDateString();
	d = d.replace(/ /g,'');
	var otherdates = $("#datecontent div").not("#"+d);
	var day1 = d.substr(0,3);
	var month1=d.substr(3,3);
	var date1=parseInt(d.substr(6,2));
	var weekstart=false;
	var weekarray=new Array();
	weekarray.push(uts);
	$(otherdates).each(function(){
		if($(this).attr('id')!=''){
		var d2 = $(this).attr('id');
		d2 = d2.substr(0,3)+' '+d2.substr(3,3)+' '+d2.substr(6,2)+' '+d2.substr(9,4);
		var uts2 = Math.round((new Date(d2)).getTime() / 1000);
		uts2 = uts2 + '';
		var week2 = parseInt(date("W",uts2));
		if(week1==week2){
			if(uts2 > uts){			
			weekarray.push(uts2);
			}
			else if(uts2 < uts){
			weekarray.unshift(uts2);
			}
		}		
		}
	});
	
	if( weekarray.length > 0){
		//append to the weekul from array
		for ( i in weekarray ){
			var cuts = weekarray[i];
			var dayli = "<li>"+date("D M j Y",cuts)+"</li>";
			$("#weekul").append($(dayli));			
		}
	}
	else{		
		var dayli = "<li>"+date("D M j Y",uts)+"</li>";
			$("#weekul").append($(dayli));			
	}    
}

function ajax(ajaxurl,d,ret,method){
if(method==undefined){
	method="POST";
}
var turn=false;
$.ajax({
         type:method,
         url :ajaxurl,         
         data:d,
         success: function(msg){		 
		 console
		 if(ret){
			 while(!turn){
			 turn=datefunction(msg);
			 }
			 /***			 
			 **/			 
			 for( i in dates ){
								var instructor = dates['course']['instructor'];						
								var title = dates['course']['title'];
							/*
							 *	COURSES
							 */
								var d = dates['course']['release_date'];
								var uuid = dates['course']['uuid'];
								var content = "<p>Course <span style='color:#C66;'><strong>"+title+"</strong></span><br>Start Date</p>";								
								appendContent(d,uuid,content);						

								var d = dates['course']['end_date'];
								var uuid = dates['course']['uuid'];
								var content = "<p>Course <span style='color:#C66;'><strong>"+title+"</strong></span><br>End Date</p>";								
								appendContent(d,uuid,content);
							/*
							 *	TESTS
							 */
							var tests = dates['test'];
							for ( j in tests){
								var test = tests[j];
								var test_title = test['title'];
								var start_date = date("D M j Y",strtotime(test['start_date']));
								var end_date   = date("D M j Y",strtotime(test['end_date']));
								// Usually tests get done within the same day..there is no harm in checking though.								
                                
								if(start_date==end_date){
								  var d = end_date;
								  var uuid = test['uuid'];
								  var content = "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span>\
								  <br>Starts At:"+date('g i A',strtotime(test['start_date']))+"\
								  <br>Ends At:"+date('g i A',strtotime(test['end_date']))+"</p>";
								  appendContent(d,uuid,content);	
								}
								else{									
									var d = start_date;
								    var uuid = test['uuid'];
									var content = "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span><br>Start Date</p>";
								    appendContent(d,uuid,content);
									
									var d = end_date;
								    var uuid = test['uuid'];
									var content = "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span><br>End Date</p>";
								    appendContent(d,uuid,content);															
								}
							}
							/*
							 *	ASSIGNMENTS
							 */
							var assignments = dates['assignments'];
							for ( j in assignments){
								var assignment = assignments[j];
								var assignment_title = assignment['title'];					
								var date_due = date("D M j Y",strtotime(assignment['date_due']));
								var date_cutoff   = date("D M j Y",strtotime(assignment['date_cutoff']));
								
								
								 if(date_due==date_cutoff){
									var d = date_due;									
								    var uuid = assignment['uuid'];
									var content = "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>Due At:"+date('g i A',strtotime(assignment['date_due']))+"<br>"+"Cutoff At:"+date('g i A',strtotime(assignment['date_cutoff']))+"</p>";
								    appendContent(d,uuid,content);
									
									var d = date_due;									
								    var uuid = assignment['uuid'];
									var content = "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>Due Date</p>";
								    appendContent(d,uuid,content);
								
									
									var d = date_cutoff;
								    var uuid = assignment['uuid'];
									var content = "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>Cutoff Date</p>";
								    appendContent(d,uuid,content);
								 }
							}			
			 }
			 /***
			 
			 **/
			 
		 $('.date-pick').datePicker({
				showOn: 'button',
				createButton:false,
				displayClose:true,
				closeOnSelect:false,
				selectMultiple:true,
				
			renderCallback:function($td, thisDate, month, year)
			{	

					for( i in dates ){
								var instructor = dates['course']['instructor'];						
								var title = dates['course']['title'];
							/*
							 *	COURSES
							 */						
                            if(thisDate.toDateString() == dates['course']['release_date']){
								$td.addClass('course');								
								/*$td.tooltip({bodyHandler: function(){
									return "<p>Course <span style='color:#C66;'><strong>"+title+"</strong></span><br>Start Date</p>";
									},showURL: false
									});*/
							}
							if(thisDate.toDateString() == dates['course']['end_date']){
								$td.addClass('course');
								/*$td.tooltip({bodyHandler: function(){
									return "<p>Course <span style='color:#C66;'><strong>"+title+"</strong></span><br>End Date</p>";
									},showURL: false
									});*/
							}
							/*
							 *	TESTS
							 */
							var tests = dates['test'];
							for ( j in tests ){
								var test = tests[j];
								var test_title = test['title'];
								var start_date = date("D M j Y",strtotime(test['start_date']));
								var end_date   = date("D M j Y",strtotime(test['end_date']));
								// Usually tests get done within the same day..there is no harm in checking though.
								//Note : this checking is useful only if the tooltip is being used
                                if((thisDate.toDateString() == start_date )&&(thisDate.toDateString() == end_date)){
								  $td.addClass('test');	
								  /*$td.tooltip({bodyHandler: function(){
								  return "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span><br>Click For More Details</p>";
									},showURL: false
									});*/
								}								
								else{
								if(thisDate.toDateString() == test['start_date']){
									$td.addClass('test');									
									/*$td.tooltip({bodyHandler: function(){
									return "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span><br>Start Date</p>";
									},showURL: false
									});*/
								}
								if(thisDate.toDateString() == test['end_date']){
									$td.addClass('test');										
									/*$td.tooltip({bodyHandler: function(){
									return "<p>Test <span style='color:#C66;'><strong>"+test_title+"</strong></span><br>End Date</p>";
									},showURL: false
									});*/
								}
								}
							}
							/*
							 *	ASSIGNMENTS
							 */
							var assignments = dates['assignments'];
							for ( j in assignments){
								var assignment = assignments[j];
								var assignment_title = assignment['title'];					
								var date_due = date("D M j Y",strtotime(assignment['date_due']));
								var date_cutoff   = date("D M j Y",strtotime(assignment['date_cutoff']));			
								
								if((thisDate.toDateString() == date_due)&&(thisDate.toDateString() == date_cutoff)){
									$td.addClass('assignment');																
									/*$td.tooltip({bodyHandler: function(){										
									return "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>Click For More Details</p>";
									},showURL: false
									});*/
								}								
								else{
								if(thisDate.toDateString() == assignment['date_due']){
									$td.addClass('assignment');																
									/*$td.tooltip({bodyHandler: function(){									
									return "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>Start Date</p>";									},showURL: false
									});*/
								}
								if(thisDate.toDateString() == assignment['date_cutoff']){
									$td.addClass('assignment');																
									/*$td.tooltip({bodyHandler: function(){
									return "<p>Assignment <span style='color:#C66;'><strong>"+assignment_title+"</strong></span><br>End Date</p>";
									},showURL: false
									});*/
								}
								}
							}
										
					}											
			}
			}
		)
		.bind(
			'click',
			function(e, selectedDate,$td,state)
			{
				
				$(this).dpDisplay();
				this.blur();
				return false;
			}
		)
		.bind(
			'dateSelected',
			function(e, selectedDate, $td, state)
			{	
			 //TODO : clear the previously selected dates
			  dayView(selectedDate);
			  weekView(selectedDate);
			  monthView(selectedDate);			 
			}
		);
		
 $('#dp').bind('focus', function() {
			  $('#dp').click();    
         });  
         $("#dp").trigger('focus');
$("#dp-popup").attr('style','top: -1026px; left: 297px;');

		 }
		$('#status').fadeOut(100);
		accord = $("#accord").accordion({active:false,clearStyle: true});
		$(accord).show();
		 }		 
});

}
function getCourseDates(){
$('#status').fadeIn(500);
ajax('/ATutor1/mods/calendar/ajax.php',"request=getdates",true); // TODO : change the ajaxurl to relative url

}

$(document).ready(function() 
{ 
var top = $("#gototop");
$(top).detach();
$("#footer").prepend($(top));
getCourseDates();
$(".week li,#weekul li").live('click',function(){
	dayView(new Date($(this).text()));
	
});
});
